package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"morleyStoneHome/model"
	"morleyStoneHome/result"
	"morleyStoneHome/service"
	"strconv"
)

type CatcoinController struct{}

func NewCatcoinController() *CatcoinController {
	return &CatcoinController{}
}

//推广接口，无邀请码直接参与，有邀请码参与并更新邀请人情况。
func (c *CatcoinController) Airdrop(ctx *gin.Context) {
	id := ctx.PostForm("capt_id")       //验证码token
	capt := ctx.PostForm("capt")        //验证码
	addr := ctx.PostForm("addr")        //ERC20地址
	invcode1 := ctx.PostForm("invcode") //邀请码
	//invcode2 := ctx.Param("invcode")
	logrus.Info("airdrop controller before verify:id, capt, addr, invcodeInt ==> ", id, ",", capt, ",", addr, ",", invcode1)
	resultRes := result.NewResult(ctx)
	if id == "" || capt == "" || addr == "" { //校验参数是否为空，除邀请码，其他都不允许为空
		resultRes.Error(1, "参数错误")
		return
	}
	var invcodeInt int
	var err error
	if "" != invcode1 {
		invcodeInt, err = strconv.Atoi(invcode1) //string邀请码转换成int类型
		if nil != err {
			logrus.Error(err)
		}
	} else {
		invcodeInt = 0 //用0表示无邀请码
	}

	if service.CaptVerify(id, capt) == true { //校验验证码是否正确
		//开始插入数据
		//logrus.Info("after verify:id, capt, addr, invcodeInt ==> ", id, ",", capt, ",", addr, ",", invcodeInt)

		msg, err := service.CatcoinService.Insert(addr, invcodeInt)
		if nil != err {
			resultRes.Error(1, err.Error())
		} else {
			resultRes.Success(msg)
		}
	} else {
		resultRes.Error(1, "参数错误")
	}
}

//查询某地址的余额、质押记录、邀请数量、提现list等信息
func (c *CatcoinController) GetOne(ctx *gin.Context) {
	resultRes := result.NewResult(ctx)
	addr := ctx.Query("eth")
	logrus.Info("getone controller : ", addr)
	if "" == addr {
		resultRes.Error(1, "参数错误")
		return
	}
	fmt.Println("param = ", addr)
	one, err := service.CatcoinService.FindOne(addr)
	if nil != err {
		resultRes.Error(1, err.Error())
		return
	}
	if nil == one {
		resultRes.Error(1, "该地址尚未参与活动")
		return
	}
	resultRes.Success(one)
}

//查询直推接口
func (c *CatcoinController) GetFollowers(ctx *gin.Context) {
	resultRes := result.NewResult(ctx)
	var cat model.Catcoin
	ctx.BindJSON(&cat)
	addr := cat.Addr
	logrus.Info("get followers controller : addr = ", addr)
	if "" == addr {
		resultRes.Error(1, "参数为空")
		return
	}
	followers, err := service.CatcoinService.FindFollowers(addr)
	if nil != err {
		resultRes.Error(1, err.Error())
		return
	}
	resultRes.Success(followers)
}
